#!/usr/bin/env bash

#################################################
#### Ensure we are in the right path. ###########
#################################################
if [[ 0 -eq $(echo $0 | grep -c '^/') ]]; then
    # relative path
    EXEC_PATH=$(dirname "`pwd`/$0")
else
    # absolute path
    EXEC_PATH=$(dirname "$0")
fi

EXEC_PATH=$(echo ${EXEC_PATH} | sed 's@/\./@/@g' | sed 's@/\.*$@@')
cd $EXEC_PATH || die "$0 Line $LINENO"
#################################################

source "../utils.sh"

TOOLS_DIR=$(dirname ${EXEC_PATH})
ROOT_DIR=$(dirname ${TOOLS_DIR})

node_cnt=3
if [[ "" != ${PRODENV_NODE_CNT} ]]; then
    x=$[1 + ${PRODENV_NODE_CNT} ]
    if [[ 0 -ne $? ]]; then
        die "$0 Line ${LINENO}: \${PRODENV_NODE_CNT} is not a number"
    fi
    node_cnt=${PRODENV_NODE_CNT}
fi

block_itv=1
if [[ "" != ${PRODENV_BLOCK_ITV} ]]; then
    x=$[1 + ${PRODENV_BLOCK_ITV} ]
    if [[ 0 -ne $? ]]; then
        die "$0 Line ${LINENO}: \${PRODENV_BLOCK_ITV} is not a number"
    fi
    block_itv=${PRODENV_BLOCK_ITV}
fi

#######################################
## Do these operations in 'Makefile' ##
#######################################
# os=$(uname -s)
# if [[ "Linux" == $os ]]; then
#     make -C ${ROOT_DIR} build_release_musl >/dev/null || die "$0 Line $LINENO"
# else
#     make -C ${ROOT_DIR} build_release >/dev/null || die "$0 Line $LINENO"
# fi
#######################################

env_name="prodenv-${RANDOM}${RANDOM}"
if [[ "" != $1 ]]; then env_name=$1; fi
env_path="/tmp/__DZK_DEV__/${env_name}"
cmd="${ROOT_DIR}/release/dzk dev"

log "Env Name: \"${env_name}\""
$cmd -d -n $env_name 2>/dev/null
if [[ -f static/root.phrase ]]; then
    $cmd -c -n $env_name -I ${block_itv} -N ${node_cnt} \
        --initial-phrase="$(cat static/root.phrase)" \
        || die "$0 Line $LINENO"
else
    $cmd -c -n $env_name -I ${block_itv} -N ${node_cnt} \
        || die "$0 Line $LINENO"
fi
log "Sleep 35 seconds..."
sleep 35

web3http_port=$(\
    ${cmd} -i -n ${env_name} \
    | grep -A 20 'Full nodes' \
    | grep 'web3_http' \
    | head -1 \
    | grep -o ': [0-9]\+' \
    | sed 's/: //'\
)
mynet="http://localhost:${web3http_port}"

#######################################
###### Run some basic test cases ######
#######################################
phrase=$(cat static/root.phrase || die "$0 Line $LINENO")
addr=$(dzk cli addrof -P "${phrase}" || die "$0 Line $LINENO")
echo "Root account: $addr"

am_of_native=$(dzk cli balance -x ${mynet} -a $addr || die "$0 Line $LINENO")
echo "Native balance of root account: $am_of_native"
if [[ "" == $am_of_native ]]; then
    die "Incorrect balance of the native token!"
fi

new_phrase=$(dzk cli gen | grep 'Phrase' | sed -r 's/^[^ ]+ //g' || die "$0 Line $LINENO")
new_addr=$(dzk cli addrof -P "${new_phrase}" || die "$0 Line $LINENO")
echo "New created account: $new_addr"

dzk cli transfer -W -x ${mynet} -f static/root.phrase -r $new_addr -n 1 >/dev/null
if [[ 0 -ne $? ]]; then die "$0 Line $LINENO"; fi; sleep 5

am_of_native=$(dzk cli balance -x ${mynet} -a $new_addr || die "$0 Line $LINENO")
echo "Native balance of new account: $am_of_native"
if [[ "1" != $am_of_native ]]; then
    die "$0 Line $LINENO: incorrect balance of the native token!"
fi

cfgfile="/tmp/batch-$(date +%s).cfg"

echo "[[\"${phrase}\",\"${addr}\",\"9.700000001\"],[\"${new_phrase}\",\"${addr}\",\"0.5\"]]" \
    > $cfgfile || die "$0 Line $LINENO"
dzk cli transfer -W -x ${mynet} -b -f $cfgfile
if [[ 0 -ne $? ]]; then die "$0 Line $LINENO"; fi; sleep 5

am_of_native1=$(dzk cli balance -x ${mynet} -a $new_addr || die "$0 Line $LINENO")
echo "Native balance of new account: $am_of_native1"
if [[ $am_of_native == $am_of_native1 ]]; then
    die "$0 Line $LINENO: incorrect balance of the native token!"
fi
#######################################
#######################################
#######################################

$cmd -S -n $env_name >/dev/null || die "$0 Line $LINENO"

for cfg in $(find ${env_path} -name "config.toml"); do
    if [[ "" == $1 ]]; then
        perl -pi -e 's/^\s*(addr_book_strict)\s*=\s*.*/$1 = true/' $cfg
    fi
done

pkg_dir="/tmp/prodenv"
pkg_name="prodenv.tar.gz"

rm -rf $pkg_dir $pkg_name 2>/dev/null
mkdir $pkg_dir || die "$0 Line $LINENO"

for ((i=0;i<${node_cnt};i++)); do
    # the first instance is seed, the second is fullnode.
    cp -r ${env_path}/$[2 + i] ${pkg_dir}/validator-${i} || die "$0 Line $LINENO"
done
cp -r ${env_path}/2 ${pkg_dir}/full-1 || die "$0 Line $LINENO"
cp -r ${env_path}/1 ${pkg_dir}/seed-1 || die "$0 Line $LINENO"
cp ${env_path}/config.json ${pkg_dir}/env_config.json || die "$0 Line $LINENO"

if [[ "" == $1 ]]; then
    rm -rf ${env_path} || die "$0 Line $LINENO"
fi

tar -C $pkg_dir -zcpf $pkg_name . || die "$0 Line $LINENO"
mv $pkg_name ${ROOT_DIR}/ || die "$0 Line $LINENO"

log "Package: ${pkg_name}"
